package com.ahnchan.ContactsPlus;

import java.util.ArrayList;

import com.ahnchan.ContactsPlus.util.ListUtils;
import com.ahnchan.ContactsPlus.util.WorldUtil;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Data;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * to show contacs detail information 
 * Long click event
 * 
 * @author Ahnchan
 *
 */
public class ContactsDetailActivity extends ListActivity {

	private ContactsPlusSetting setting;

	public static final String ID_DATA = "ID";
	public static final String NAME_DATA = "NAME";

	private ContactsDetailAdapter mContactsDetailAdapter;
	
	private ArrayList<ContactDetail> aList;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {

    	super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_detail);

        setting = ContactsPlusSetting.instatnce();

        String strID = getIntent().getStringExtra(ID_DATA);
        String strName = getIntent().getStringExtra(NAME_DATA);

        // Set dialog label
        this.setTitle(strName);
        
        // Name label
       	TextView title = (TextView)findViewById(R.id.contact_detail_title);
    	title.setText(strName);
    	title.setTextSize(setting.getIndexFontSize());
    	title.setBackgroundColor(setting.getIndexTitleBGColor());
    	title.setTextColor(setting.getIndexTitleColor());

        // List click
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        lv.setOnItemClickListener(new OnItemClickListener() {
        	/**
        	 * Show contact info
        	 */
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Log.e("ContactsPlus", "[ContactsDetailActivity] item click");

				ContactDetail contactDetail = aList.get(arg2);
				
				actionContact(arg1, contactDetail);
			}
        });
                
        setText("ID : " + strID + "," + strName);
        
        // Get contact list
        showContactDetail(strID);
        
    }
    
    public void actionHandler(View v) {
    	
    	// Find position
        ListView list = getListView();
        int iPos = list.getPositionForView(v);
        
        // get Contact information
        ContactDetail contact = (ContactDetail)aList.get(iPos);
        
        int iType = contact.getType();
        String strData = contact.getData();
        
        if (iType == ContactDetail.TYPE_MOBILE) {
        	sendSMS(strData);
        } else {
        	// do nothing
        }
    }

    /**
     * to send email, to call mobile, home, office...
     * 
     * @param view
     * @param contact
     */
    private void actionContact(View view, ContactDetail contact) {
    
    	int iType = contact.getType();
    	String strData = contact.getData();

    	switch(iType) {
    		case ContactDetail.TYPE_HOME :
    			callPhone(strData);
    			break;

    		case ContactDetail.TYPE_FAX :
    			callPhone(strData);
    			break;
    			
    		case ContactDetail.TYPE_MOBILE :
    			callPhone(strData);
    			break;
    			
    		case ContactDetail.TYPE_EMAIL :
    			sendEmail(strData);
    			break;
    	}
    }
    
    /**
     * call phone 
     * @param phone
     */
    private void callPhone(String phone) {

    	Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
    	startActivity(intent);
    	
    }

    /**
     * call video phone
     * @param phone
     */
    private void callVideoPhone(String phone) {
    	// TODO
    	// find video-call method
//    	Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
//    	startActivity(intent);

    }
    
    /**
     * write message to send SMS
     * 
     * @param phone
     */
    private void sendSMS(String phone) {
    	
    	Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
    	startActivity(intent);
    	
    }
    
    /**
     * write email 
     * 
     * @param email
     */
    private void sendEmail(String email) {

    	Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"+email));
    	startActivity(intent);
    	
    }
    
    /**
     * Custom Detail Simple Adapter Class
     * Change Font size, control contacts photo size
     * Bind Image
     */
    class ContactsDetailAdapter extends BaseAdapter implements SectionIndexer {
    	
    	private Context context;
    	private ArrayList<ContactDetail> conList;
    	
		/**
    	 * Constructor
    	 */
		public ContactsDetailAdapter(Context _context, ArrayList<ContactDetail> list) {
			context = _context;
			conList = list;
		}
		
		public int getCount() {
			return conList.size();
		}
		
		public Object getItem(int position) {
			return conList.get(position);
		}
		
		/**
		 * Bind information
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.contact_detail_row, parent, false);
			
			//Bind data
			ContactDetail contactDetail = conList.get(position);
			String strType = contactDetail.getTypeName();
			int iType = contactDetail.getType();
			
			// Type (Debug, Don't delete - Ahnchan 20110403)
			TextView type = (TextView) row.findViewById(R.id.data_type);
			type.setTextSize(setting.getIntFontSize());
			type.setText(strType);
			
			// Data (Phone number, Mobile number, E-Mail ...)
			TextView data = (TextView) row.findViewById(R.id.data_text);
			data.setTextSize(setting.getIntFontSize());
			String strData = contactDetail.getData();
			if (contactDetail.getType() == ContactDetail.TYPE_HOME ||
				contactDetail.getType() == ContactDetail.TYPE_FAX ||
				contactDetail.getType() == ContactDetail.TYPE_MOBILE) {
				
				strData = WorldUtil.chagePhoneNumber(contactDetail.getData(),
						setting.getLanguage(),
						setting.getCountry(), 
						contactDetail.getType());
			}
			data.setText(strData);
			
			// Contact Image
			ImageView imageContact = (ImageView) row.findViewById(R.id.image_contact);
			if (iType == ContactDetail.TYPE_HOME) {
				imageContact.setImageResource(R.drawable.ic_detail_phone);
			} else if (iType == ContactDetail.TYPE_FAX) {
				imageContact.setImageResource(R.drawable.ic_detail_fax);
			} else if (iType == ContactDetail.TYPE_MOBILE) {
				imageContact.setImageResource(R.drawable.ic_detail_mobile);
			} else if (iType == ContactDetail.TYPE_EMAIL) {
				imageContact.setImageResource(R.drawable.ic_detail_email);
			} else {
				imageContact.setImageResource(R.drawable.ic_detail_blank);
			}
			
			// Action1 Image
			ImageView actionImage1 = (ImageView) row.findViewById(R.id.image_act1);
			if (iType == ContactDetail.TYPE_MOBILE) {
				// Mobile Phone
				actionImage1.setImageResource(R.drawable.ic_detail_sms);
			} else if (iType == ContactDetail.TYPE_EMAIL) {
				// EMail
				actionImage1.setImageResource(R.drawable.ic_detail_blank);
			} else {
				// Phone, FAX...
				actionImage1.setImageResource(R.drawable.ic_detail_blank);
			}
			
			return row;
		}
		
		public void setSection(LinearLayout header, String firstChar) {
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public int getPositionForSection(int section) {
			return -1;
		}

		public int getSectionForPosition(int arg0) {
			return 0;
		}

		public Object[] getSections() {
			return null;
		}
    }
	
    /**
     * Get contact information
     */
    private void showContactDetail(String id) {
    	
    	if (null == id) return;
    	if ("".equals(id)) return;
    	
	    // Initialization list	
    	aList = new ArrayList<ContactDetail>();

    	mContactsDetailAdapter = new ContactsDetailAdapter(this, aList);
    	setListAdapter(mContactsDetailAdapter);
    	
    	// where
    	String[] projection_data;
    	
    	// select
    	String selection = "" ;
    	
    	// Order by
    	String order = "";
    	
    	// Cursor
    	Cursor mCursor;

    	//----------------------------------------------
    	// Get Phone number
    	//----------------------------------------------
    	
		projection_data = new String[] {
        			ContactsContract.CommonDataKinds.Phone.DATA1,
        			ContactsContract.CommonDataKinds.Phone.DATA2,
        			ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
    	};
		
		selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = '" + id + "'";
    	
    	mCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
        										projection_data, selection, null, order);
    		
    	if (mCursor == null) {
    		return;
    	}
    	
    	if (mCursor.moveToFirst()) {
    		int iTotal = 0;
    		String strOrgID = "";
    		
    		do {

    			int iType = mCursor.getInt(1);
    			String strData = mCursor.getString(0);
    			
    			switch (mCursor.getInt(1)) {
	    			case CommonDataKinds.Phone.TYPE_MOBILE :
	    				iType = ContactDetail.TYPE_MOBILE;
	    				break;
	    			case CommonDataKinds.Phone.TYPE_FAX_HOME :
	    			case CommonDataKinds.Phone.TYPE_FAX_WORK :
	    				iType = ContactDetail.TYPE_FAX;
	    				break;
	    			default :
	    				iType = ContactDetail.TYPE_HOME;
    			}

    			ContactDetail contactDetail = new ContactDetail(iType, strData);
    			aList.add(contactDetail);
    			
    			iTotal++;
				
//				strOrgID = strID;
    	
    		} while (mCursor.moveToNext());
    		
    		// Debug Info
    		setText("Count:" + iTotal + ", " + id + ", " + setting.getLanguage());
    		
    	}
    	
    	mCursor.close();
    	
    	//----------------------------------------------
    	// Get E-Mail
    	//----------------------------------------------
		projection_data = new String[] {
    			ContactsContract.CommonDataKinds.Email.DATA1,
    			ContactsContract.CommonDataKinds.Phone.DATA2,
    			ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
		};
	
		selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = '" + id + "'";
	
		mCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
    										projection_data, selection, null, order);
		
		if (mCursor == null) {
			return;
		}
		
		if (mCursor.moveToFirst()) {
			int iTotal = 0;
			String strOrgID = "";
			
			do {
	
				int iType = 0;
				String strData = mCursor.getString(0);
				
				// Skip duplicate contact info
	//			if (strOrgID.equals(strID)) {
	//				continue;
	//			}
				
				iType = ContactDetail.TYPE_EMAIL;
				ContactDetail contactDetail = new ContactDetail(iType, strData);
				aList.add(contactDetail);
				
				iTotal++;
		
			} while (mCursor.moveToNext());
			
			// Debug Info
			setText("Count:" + iTotal + ", " + id);
			
		}
	
		mCursor.close();
    	
    	return;
    }
    
	/**
	 * Debug Text view
	 * @param message
	 */
    private void setText(String message) {
    	TextView text = (TextView)findViewById(R.id.contact_list_text);
    	text.setText(message);
    }
}